#include "SAView.h"

#include <QStringList>
#include <QSplitter>
#include <QBoxLayout>
#include <QVBoxLayout>
#include <QDir>
#include <QDebug>
#include <QApplication>
#include <QTime>
#include <QMessageBox>

#include "treemodel.h"
#include "plot/plotWidget.h"

#include "SAQueryConf.h"
#include "SATable.h"
#include "SAThread.h"

SAView::SAView(QWidget *parent, Qt::WindowFlags f)
     : QWidget(parent,f)
     , dbDir("")
{
	init();
}

SAView::~SAView()
{
    try{
        // ptr_AGCThread->terminate();
        if (NULL!=ptr_SAThread)
        {
            delete ptr_SAThread;
            ptr_SAThread = NULL;
        }
        if (NULL!=ptr_PlotWidget)
        {
            delete ptr_PlotWidget;
            ptr_PlotWidget = NULL;
        }
        if (NULL!=ptr_SATableView)
        {
            delete ptr_SATableView;
            ptr_SATableView = NULL;
        }
        if (NULL!=ptr_SAQueryConfView)
        {
            delete ptr_SAQueryConfView;
            ptr_SAQueryConfView = NULL;
        }
        qDebug() << "SAView::destroy\n";
    }catch(...){
        qDebug() << "SAView::destroy fail\n";
    }
}

void SAView::init()
{
    QStringList cheaders;
    cheaders <<tr("devid")<<tr("idx")<<tr("dtime")<<tr("value");
    TreeModel *cmodel= new TreeModel(cheaders,TreeModel::SA_View);
    ptr_SATableView = new SATableView(cmodel,this);

    ptr_PlotWidget = new PlotWidget();

    ptr_SAQueryConfView = new SAQueryConfView();
    connect(ptr_SAQueryConfView,SIGNAL(fileSelect(QString)),this,SLOT(fileSelect(QString)));
    connect(ptr_SAQueryConfView,SIGNAL(ReloadSA()),this,SLOT(loadSAData()));
    connect(ptr_SAQueryConfView,SIGNAL(draw(int,int)),this,SLOT(itemDoubleClick(int,int)));
    connect(ptr_SAQueryConfView,SIGNAL(resetCurveType(int)),this,SLOT(resetCurveType(int)));

    QSplitter *h_QSplitter = new QSplitter(this);
    h_QSplitter->setContentsMargins(0,0,0,0);
    h_QSplitter->setOrientation(Qt::Horizontal);
    h_QSplitter->addWidget(ptr_SAQueryConfView);
    h_QSplitter->addWidget(ptr_SATableView);
    h_QSplitter->setStretchFactor(0,1);
    h_QSplitter->setStretchFactor(1,5);

	QSplitter *v_QSplitter = new QSplitter();
    v_QSplitter->setContentsMargins(0,0,0,0);
    v_QSplitter->setOrientation(Qt::Vertical);
    v_QSplitter->addWidget(h_QSplitter);
    v_QSplitter->addWidget(ptr_PlotWidget);
    v_QSplitter->setStretchFactor(0,1);
    v_QSplitter->setStretchFactor(1,1);

    QBoxLayout *ptr_QLayout = new QBoxLayout(QBoxLayout::TopToBottom,this);
    ptr_QLayout->setContentsMargins(0,0,0,0);
    ptr_QLayout->addWidget(v_QSplitter);

    ptr_SAThread = new SAThread();
    qRegisterMetaType<SADataItem>("SADataItem");
    qRegisterMetaType<QList<SADataItem> >("QList<SADataItem>");
    connect(ptr_SAThread,SIGNAL(newItem(QList<SADataItem>))
        ,this,SLOT(addNewItem(QList<SADataItem>)));
    ptr_SAThread->start();

    this->setContentsMargins(0,0,0,0);
}

// void SAView::agcDetailCheck(QString _dv,QString _cz)
// {
//     ptr_SAThread->stopRead();
//     ptr_AGCTreeView->clear();
//     ptr_AGCTableView->clear();
//     ptr_PlotWidget->clear();
//     ConfDeal *ptr_ConfDeal = ConfDeal::getInstance();
//     QString _dirPath =  ptr_ConfDeal->getsqliteDir()+ptr_ConfDeal->getpathDiv()+_dv+ptr_ConfDeal->getpathDiv()+"000";
//     QDir dir = _dirPath;
//     if (!dir.exists()) {
//         if (!dir.mkpath(_dirPath)){
//             qDebug() << "Can't create " + _dirPath;
//         }
//     }
//     cz_agc_path = _dirPath+ptr_ConfDeal->getpathDiv()+_cz+".db3";
//     if (!QFile::exists(cz_agc_path))
//     {
//         /* code */
//         qDebug() << QString("db file:%1 is not exists\n").arg(cz_agc_path);
//         ptr_AGCTreeView->setModify(true);
//         ptr_AGCTreeView->createAgcTree(_cz);
//         return;
//     }else{
//         ptr_AGCTreeView->setModify(false);
//     }
//     // qDebug() << QString("opendb curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));

//     if(!ptr_AGCThread->openDB(cz_agc_path))
//     {
//         return;
//     }
//     // qDebug() << QString("load data curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
//     long long _startT=0;
//     long long _endT=0;
//     if (ptr_AGCThread->loadDBConf(_startT,_endT))
//     {
//         /* code */
//         // qDebug() << QString("load conf curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
//         QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
//         ptr_AGCTreeView->createAgcTree(_cz,ptr_AGCThread->_agcdefs,ptr_AGCThread->_agcpros);
//         ptr_AGCQueryConfView->setTimeRegion(_startT,_endT);
//         QApplication::restoreOverrideCursor();
//         // qDebug() << QString("end display conf curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
//     }else{
//         qDebug() << QString("load conf fail\n").arg(cz_agc_path);
//         return;
//     }
//     loadAGCData();
// };

void SAView::fileSelect(QString _name)
{
    if(ptr_SAThread->openDB(_name))
    {
        getTimeZone();
    }
}

void SAView::loadSAData()
{
    long long _startT=0;
    long long _endT=0;
    ptr_SAQueryConfView->getTimeRegion(_startT,_endT);
    if (_startT>=_endT)
    {
        QMessageBox::warning(this,tr("warning"),tr("start time more then end time, please reset it!"),QMessageBox::Ok);
        return;
    }
    // qDebug()<<_startT<<";"<<_endT;
    // ptr_SAThread->stopRead();
    ptr_SATableView->clear();
    ptr_PlotWidget->clear();
    QSet<int> _devids;
    QSet<int> _idxs;
    if (ptr_SAThread->loadDBData(_startT,_endT,_devids,_idxs))
    {
        qDebug() << QString("display data curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        ptr_SATableView->createDataList(ptr_SAThread->_datas);
        QApplication::restoreOverrideCursor();
        qDebug() << QString("end display data curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
    }else{
        qDebug() << QString("dir conf data is empty\n").arg(dbDir);
    }
    ptr_SAQueryConfView->setDevIDList(_devids);
    ptr_SAQueryConfView->setIDXList(_idxs);
    // ptr_SAThread->startRead();
}

void SAView::getTimeZone()
{
    long long _startT=0;
    long long _endT=0;
    if(ptr_SAThread->getNewTimeRange(_startT,_endT))
    {
        ptr_SAQueryConfView->setTimeRegion(_startT,_endT);
    }
};

void SAView::resetCurveType(int _curveType)
{
    switch(_curveType)
    {
        case 0:
            ptr_PlotWidget->resetItemDrawStyle("Lines");
            break;
        case 1:
            ptr_PlotWidget->resetItemDrawStyle("Steps");
            break;
        case 2:
            ptr_PlotWidget->resetItemDrawStyle("Sticks");
            break;
        default:
            ptr_PlotWidget->resetItemDrawStyle("Lines");
            break;
    }
}

void SAView::itemDoubleClick(int _devid,int _idx)
{
    QMap<QString,QMap<QDateTime,qreal> > _draws;
    QMap<QString,LimitData> val_limit;
    // qDebug() << QString("getDrawData curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
    if (ptr_SAThread->getDrawData(_draws,val_limit,_devid,_idx))
    {
        // qDebug() << QString("drawItems curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        ptr_PlotWidget->drawItemsDatas(_draws);
        QApplication::restoreOverrideCursor();
        // qDebug() << QString("end drawItems curT=%1\n").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
        QString _msg;
        for(QMap<QString,LimitData>::iterator it = val_limit.begin();it!=val_limit.end();it++)
        {
            _msg += QString("point[%1] min[%2,%3],max[%4,%5] ")
            .arg(it.key())
            .arg(it.value().min_dt_STR).arg(double(it.value().minValue), 0, 'f', 3)
            .arg(it.value().max_dt_STR).arg(double(it.value().maxValue), 0, 'f', 3);
        }
        emit showMsg(_msg);
    }else{
        ptr_PlotWidget->clear();
    }
}

void SAView::addNewItem(QList<SADataItem> _data)
{
    ptr_SATableView->addDataToList(_data);
}
